package com.example.controller;

import com.example.Dto.UserDto;
import com.example.domain.User;
import com.example.service.IUserService;
import com.example.utils.R;
import com.example.utils.SMSUtils;
import com.example.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 短信发送功能
     * @param user 用户信息
     * @param session 将验证码存储到session中
     * @return 响应页面数据
     */
    @RequestMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        //获取验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info(code);
        //将验证码存储到Redis缓存数据库中并设置有效时间为5分钟
        redisTemplate.opsForValue().set("code",code,5, TimeUnit.MINUTES);
        //发送短信
        //SMSUtils.sendMessage("瑞吉外卖","","",phone);
        return new R(1,"短信发送成功");
    }

    /**
     * 登录功能
     * @param userDto 用户的登录信息
     * @param session 将用户id存储到session域中
     * @return 响应到页面的数据
     */
    @RequestMapping("/login")
    public R login(@RequestBody UserDto userDto,HttpSession session){
        String code = (String) redisTemplate.opsForValue().get("code");
        Long userId = userService.save(userDto, code);
        session.setAttribute("user",userId);
        //登录成功之后验证码就没用了直接删除
        redisTemplate.delete("code");
        return new R(1,"登录成功");
    }
}
